package net.tycmc.bulb.dbutil.global;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.tycmc.cty.ctyms.timejob.common.MyConnectDSDAO;

import org.apache.commons.configuration.ConfigurationException;

import com.tycmc.functions.util.DynamicReadConfig;

public class DBInfoListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	//tomcat启动时初始化数据库链接信息，采用数据库直连的方式从数据库中获取信息
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		String sql = "select * from DataBaseInfo where getdate()>=DBInfo_Eff and getdate()<DBInfo_Exp";
		MyConnectDSDAO mcdsDAO = new MyConnectDSDAO();
		List<Map<String,Object>> databaselist=mcdsDAO.execQuery(sql, new Object[]{});
		
		String sql_MS = "select top 1 * from DataBaseInfo where DBInfo_Type=6 and getdate()>=DBInfo_Eff and getdate()<DBInfo_Exp";
		Map<String,Object> dbMS = mcdsDAO.execQueryOne(sql_MS, new Object[]{});
		
		if(databaselist.size()>0){
			GlobalDBVar.dbMap = new HashMap<String,Object>();
			GlobalDBVar.dbMonthMap = new HashMap<String,Object>();
			GlobalDBVar.dbMSBak = new HashMap<String,Object>();
			String SetDBType ="";
			try {
				SetDBType = DynamicReadConfig.getConfigProperty("config.properties", "SetDBType");
			} catch (ConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(SetDBType.equals("1")){//1：openrowset；
				DBInfoService.openrowset(databaselist,dbMS);
			}else if(SetDBType.equals("2")){//2：数据库远程服务器链接
				DBInfoService.databaselong(databaselist,dbMS);
			}else {
				System.out.println("config.properties表中未设定SetDBType值，或该值在1和2之外！");
			}
			GlobalDBVar.isOk = true;
		}else{
			System.out.println("*********ERROR******DBInfoListener**********:数据库链接信息初始化失败，DataBaseInfo表中没有值，请初始化数据并重新启动！！！！！！");
		}
		
		//释放内容
		databaselist=null;
	}
	
}
